<template>
  <div class="Pagination">
    <button
      :disabled="currentPageNo === 1"
      @click="$emit('changPageNo', currentPageNo - 1)"
    >
      上一页
    </button>
    <button v-if="starEnd.star !== 1" @click="$emit('changPageNo', 1)">
      1
    </button>
    <button v-if="starEnd.star > 2">...</button>

    <button
    v-if="page >= starEnd.star"
    :class="{active:currentPageNo === page}"  
    @click="$emit('changPageNo',page)"
     v-for="page in starEnd.end"
    :key="page"
    >{{page}}</button>

    <button v-if="starEnd.end < totalPageNo">...</button>
    <button v-if="starEnd.end < totalPageNo" @click="$emit('changPageNo', 5)">
      {{ totalPageNo }}
    </button>
    <button
      :disabled="currentPageNo === totalPageNo"
      @click="$emit('changPageNo', currentPageNo + 1)"
    >
      下一页
    </button>
    <button>共{{ totalPageNo }}页</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  //  <!--pagerCount连续页数,一般都是奇数-->
  //  <!--total页面总数-->
  //  <!--pageSize当前页面数据数量-->
  //  <!--currentPageNo第几页的数据-->
  props: {
    pagerCount: {
      type: Number,
      default: 0,
    },
    total: {
      type: Number,
      default: 0,
    },
    pageSize: {
      type: Number,
      default: 5,
      require: true,
    },
    currentPageNo: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {};
  },
  computed: {
    //总页数
    totalPageNo() {
      return Math.ceil(this.total / this.pageSize);
    },
    //连续页起始结束位置
    starEnd() {
      let { currentPageNo, pagerCount, totalPageNo } = this;
      let star = 0;
      let end = 0;
      if (pagerCount >= totalPageNo) {
        star = 1;
        end = totalPageNo;
      } else {
        star = currentPageNo - Math.floor(pagerCount / 2);
        end = currentPageNo + Math.floor(pagerCount / 2);
        if (star < 1) {
          star = 1;
          end = pagerCount;
        }
        if (end > totalPageNo) {
          end = totalPageNo;
          star = totalPageNo - pagerCount + 1;
        }
      }
      return { star, end };
    },
  },
};
</script>

<style lang="less" scoped>
.Pagination {
  margin: 0 300px;
  button {
    border: 0;
    height: 28px;
    margin: 0 5px;
    padding: 0 4px;
    font-size: 14px;
    color: #606266;
    line-height: 28px;
    min-width: 35px;
    border-radius: 2px;
    text-align: center;
    display: inline-block;
    box-sizing: border-box;
    background-color: #f4f5f5;

    // []选择带有改属性的组件设置样式，cursor:not-allowed;禁用默认行为
    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }
    &.active {
      cursor: not-allowed;
      background-color: #f54;
      color: #fff;
    }
  }
}
</style>
